
import { InjectRepository } from '@nestjs/typeorm';
import {Repository, Not, In, Like, DataSource} from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateSurveyDto, UpdateSurveyDto, QuerySurveyDto } from './dto/survey.dto';
import { SurveyEntity } from './entities/survey.entity';
import {SurveyUserEntity} from "./entities/survey-user.entity";
import {StudentEntity} from "../../eduation/student/entities/student.entity";
import {SurveyIssueEntity} from "./entities/survey-issue.entity";
import {CacheEnum} from "../../../common/enum";

@Injectable()
export class SurveyService {
    constructor(
        private dataSource: DataSource,
        @InjectRepository(SurveyEntity)
        private readonly surveyEntityRep: Repository<SurveyEntity>,
        @InjectRepository(SurveyUserEntity)
        private readonly surveyUserEntityRep: Repository<SurveyUserEntity>,
        @InjectRepository(StudentEntity)
        private readonly studentEntityRep:  Repository<StudentEntity>,
        @InjectRepository(SurveyIssueEntity)
        private readonly surveyIssueEntityRep:  Repository<SurveyIssueEntity>,
    ) {}
    async create(createSurveyDto: CreateSurveyDto) {
        const res = await this.surveyEntityRep.save(createSurveyDto);
        return ResultData.ok(res);
    }

    async findAll(query :QuerySurveyDto ) {
        const entity = this.surveyEntityRep.createQueryBuilder('entity');
        entity.where({ delFlag: '0'});
        if(query.surId){
            entity.andWhere("entity.surId = :surId", {surId: query.surId});
        }
        if(query.surType){
            entity.andWhere("entity.surType = :surType", {surType: query.surType});
        }
        if(query.status){
            entity.andWhere("entity.status = :status", {status: query.status});
        }
        if(query.createBy){
            entity.andWhere("entity.createBy = :createBy", {createBy: query.createBy});
        }
        if(query.params?.beginTime && query.params?.endTime){
            entity.andWhere("entity.createTime BETWEEN :start AND :end", { start: query.params.beginTime, end: query.params.endTime });
        }
        if(query.updateBy){
            entity.andWhere("entity.updateBy = :updateBy", {updateBy: query.updateBy});
        }
        if(query.params?.beginTime && query.params?.endTime){
            entity.andWhere("entity.updateTime BETWEEN :start AND :end", { start: query.params.beginTime, end: query.params.endTime });
        }
        if(query.remark){
            entity.andWhere("entity.remark = :remark", {remark: query.remark});
        }
        if(query.tempName){
            entity.andWhere("entity.tempName LIKE :tempName", {tempName: `%${query.tempName}%`});
        }
        if(query.surName){
            entity.andWhere("entity.surName LIKE :surName", {surName: `%${query.surName}%`});
        }
        if(query.params?.beginTime && query.params?.endTime){
            entity.andWhere("entity.startTime BETWEEN :start AND :end", { start: query.params.beginTime, end: query.params.endTime });
        }
        if(query.params?.beginTime && query.params?.endTime){
            entity.andWhere("entity.endTime BETWEEN :start AND :end", { start: query.params.beginTime, end: query.params.endTime });
        }
        if(query.isTemplate){
            entity.andWhere("entity.isTemplate = :isTemplate", {isTemplate: query.isTemplate});
        }
        if(query.isPublic){
            entity.andWhere("entity.isPublic = :isPublic", {isPublic: query.isPublic});
        }
        if(query.repeatJoin){
            entity.andWhere("entity.repeatJoin = :repeatJoin", {repeatJoin: query.repeatJoin});
        }
        if (query.orderByColumn && query.isAsc) {
            const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
            entity.orderBy(`entity.${query.orderByColumn}`, key);
        }

        // 如果没有分页参数则返回所有数据
        if (!query.pageSize || !query.pageNum) {
            const list = await entity.getMany();
            return ResultData.ok(list);
        }

        entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
        const [list, total] = await entity.getManyAndCount();

        return ResultData.ok({
            list,
            total,
        });
    }

    async findOne(id: number) {
        const res = await this.surveyEntityRep.findOne({
            where: {
                delFlag: '0',
                surId: id,
            },
        });
        if(!res){
            return ResultData.fail(500,'问卷不存在');
        }
        // 找到关联的学生ID和信息
        let joinUserList: SurveyUserEntity[];
        // @ts-ignore
        joinUserList = await this.surveyUserEntityRep.find({
            where: {
                surId: id,
            },
        })
        if(joinUserList.length){
            (res as any).joinUserData =  await this.studentEntityRep.find({
                where: {
                    studentId : In(joinUserList.map(item => item.userId))
                },
                select: ['studentId', 'studentName', 'studentNumber', 'phone', 'oldName', 'gender', 'birthday'],
            })
        }else{
            (res as any).joinUserData = []
        }
        (res as any).joinUserList = joinUserList.map(item => item.userId);
        return ResultData.ok(res);
    }

    async update(updateSurveyDto: UpdateSurveyDto) {
        const { joinUserList,...data } = updateSurveyDto
        const res = await this.surveyEntityRep.update({  surId: data.surId }, data);
        // 删除关联表中信息
        await  this.surveyUserEntityRep.delete({ surId: updateSurveyDto.surId })
        // 同步最新信息
        await  this.surveyUserEntityRep.insert(joinUserList.map(item=>{
            let data = new SurveyUserEntity();
            data.userId = item as number;
            data.surId = updateSurveyDto.surId;
            data.score = 0;
            data.joined = 0;
            return data;
        }))
        return ResultData.ok({value:res.affected >= 1});
    }

    async remove(surIds: number[]) {
        const res = await this.surveyEntityRep.update(
            { surId: In(surIds) },
            {
                delFlag: '1',
            },
        );
        return ResultData.ok({value:res.affected >= 1});
    }

    /**
     * 更新问卷状态
     */
    async updateSurveyStatus() {
        const now = new Date();
        // 找到需要更新为"收集中"(state=3)的问卷
        await this.surveyEntityRep
            .createQueryBuilder()
            .update(SurveyEntity)
            .set({ state: '3' })
            .where({ state: '2' })
            .andWhere('startTime <= :now', { now })
            .andWhere('endTime > :now', { now })
            .andWhere('delFlag = 0')
            .execute();

        // 找到需要更新为"已完成"(state=4)的问卷
        await this.surveyEntityRep
            .createQueryBuilder()
            .update(SurveyEntity)
            .set({ state: '4' })
            .where({ state: '3' })
            .andWhere('endTime <= :now', { now })
            .andWhere('delFlag = 0')
            .execute();
    }

    /**
     * 克隆问卷
     * @param surId 问卷ID
     * @param other
     */
    async cloneOne(surId: number,other:any) {
        // 找到原来的问卷数据
        const data = await this.surveyEntityRep.findOne({
            where: {
                surId: surId,
            },
        });
        delete  data.surId;
        data.endTime = ''
        data.startTime = ''
        data.state = '1'
        // 找到原来的问题数据
        const issueData = await this.surveyIssueEntityRep.find({
            where: {
                surId: surId,
            },
        })
        // 找到原来的问卷参与人员数据
        const joinUserData = await this.surveyUserEntityRep.find({
            where: {
                surId: surId,
            },
        })
        const queryRunner = this.dataSource.createQueryRunner();
        await queryRunner.connect();
        await queryRunner.startTransaction();
        try {
            // 创建新问卷
            const res:SurveyEntity = await queryRunner.manager.save(SurveyEntity,{ ...data,...other});
            // 新问卷关联题目
            const newIssueData = issueData.map(item=>{
                delete item.id;
                item.surId = res.surId;
                return item;
            })
            await queryRunner.manager.save(SurveyIssueEntity,newIssueData);
            // 新问卷关联用户
            const newUserData = joinUserData.map(item=>{
                delete item.id;
                item.surId = res.surId;
                item.joined =  0
                item.score = 0
                return item;
            })
            await queryRunner.manager.save(SurveyUserEntity,newUserData);
            await queryRunner.commitTransaction();
            return ResultData.ok();
        } catch (error) {
            console.log(error)
            await queryRunner.rollbackTransaction();
            return ResultData.fail(500,`拷贝失败：${error.message}`);
        } finally {
            await queryRunner.release();
        }
    }
}
